package com.qiaoda.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiaoda.entity.FenJLBean;
import com.qiaoda.model.Resume;
import com.qiaoda.service.ResumeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/13 0013.
 *
 * 关键字	例子	Elasticsearch查询语句
 And	findByNameAndPrice	{"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}
 Or	findByNameOrPrice	{"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}
 Is	findByName	{"bool" : {"must" : {"field" : {"name" : "?"}}}}
 Not	findByNameNot	{"bool" : {"must_not" : {"field" : {"name" : "?"}}}}
 LessThanEqual	findByPriceLessThan	{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
 GreaterThanEqual	findByPriceGreaterThan	{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}
 Before	findByPriceBefore	{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
 After	findByPriceAfter	{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}
 Like	findByNameLike	{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}
 StartingWith	findByNameStartingWith	{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}
 EndingWith	findByNameEndingWith	{"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}}
 Contains/Containing	findByNameContaining	{"bool" : {"must" : {"field" : {"name" : {"query" : "?","analyze_wildcard" : true}}}}}
 In	findByNameIn(Collectionnames)	{"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}
 NotIn	findByNameNotIn(Collectionnames)	{"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}}
 Near	findByStoreNear	暂不支持
 True	findByAvailableTrue	{"bool" : {"must" : {"field" : {"available" : true}}}}
 False	findByAvailableFalse	{"bool" : {"must" : {"field" : {"available" : false}}}}
 OrderBy	findByAvailableTrueOrderByNameDesc	{"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}}

 创建查询

 Spring Data repository自带了一个非常有用的查询构造器。它会从方法名中去掉类似find..By,read...By,query...By,count...By之类的前缀，然后解析剩余的名字。我们也可以在方法名中加入更多的表达式，比如查询时需要distinct约束,那么在方法名中加入Distinct即可。方法名中的第一个By是一个分解符，代表着查询语句的开始，我们可以用And或Or来将多个查询条件关联起来。
 Example 6.Query creation from method names(通过方法名创建查询)
 public interface PersonRepository extends Repository<User, Long> {

 List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

 // Enables the distinct flag for the query
 // 在查询中使用distinct约束
 List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
 List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

 // Enabling ignoring case for an individual property
 // 忽略大小写 在方法名中加入IgnoreCase
 List<Person> findByLastnameIgnoreCase(String lastname);
 // Enabling ignoring case for all suitable properties
 // 所有属性都忽略大小写 在方法名中加入AllIgnoreCase
 List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

 // Enabling static ORDER BY for a query
 // 排序 在方法名中加入OrderBy
 List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
 List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
 }
 对方法名的解析结果取决于实际要操作的数据库/搜索引擎是什么。另外，还有一些普遍的问题要注意:
 在方法名中，可以使用And和Or连接多个属性。除此之外还可以使用Between,LessThan,GreaterThan,Like等等，不同数据库支持的连接符是不一样的，需要查看相关文档
 可以使用IgnoreCase来忽略单个属性的大小写，比如findByLastnameIgoreCase,也可以使用AllIgnoreCase来忽略全部属性的大小写。前提是，实际选择的数据库/搜索引擎支持。
 可以使用OrderBy来对相关属性进行排序。具体是升序还是降序，是通过Asc和Desc控制的。如果想了解动态排序，请看处理特殊参数。

 *
 */
@RestController
public class ResumeController {

    @Autowired
    private ResumeRepository resumeRepository;

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/saveResume")
    public Object saveResume() {
        for (int i=3000; i<4000; i++) {
            try {
                String url = "http://localhost:80/test/search?rows=1&offset="+i;
                String forObject = restTemplate.getForObject(url, String.class);
                String substring = forObject.substring(1, forObject.length() - 1);
                JSONObject parse1 = (JSONObject) JSONObject.parse(substring);
                Resume resume = new Resume();
                resume.setMobile(parse1.get("mobile_s").toString());
                resume.setTemplateId(parse1.get("template_id").toString());
                resume.setDegreeCn(parse1.get("degree_cn").toString());
                resume.setHjob(parse1.get("hjob").toString());
                resume.setArrivalTime(parse1.get("arrival_time").toString());
                resume.setPoliticsStatus(parse1.get("politics_status").toString());
                resume.setSchools(parse1.get("schools").toString());
                resume.setOriginalFilePath(parse1.get("original_file_path").toString());
                resume.setGender((Integer) parse1.get("gender"));
                resume.setJobIntension(parse1.get("job_intension").toString());
                resume.setLastTrade(parse1.get("last_trade").toString());
                resume.setAge((Integer) parse1.get("age_i"));
                resume.setLastCompany(parse1.get("last_company").toString());
                resume.setSalaryFrom((Integer) parse1.get("salary_from_i"));
                resume.setJob(parse1.get("job").toString());
                resume.setSelfAssessment(parse1.get("self_assessment").toString());
                resume.setGenderCn(parse1.get("gender_cn").toString());
                resume.setUpdateTime(parse1.get("update_time").toString());
                resume.setCreateTime(parse1.get("create_time").toString());
                resume.setBirthday(parse1.get("birthday").toString());
                resume.setDegreeId((Integer) parse1.get("degree_id"));
                resume.setWorkYears((Integer) parse1.get("work_years_i"));
                resume.setTrade(parse1.get("trade").toString());
                resume.setState(parse1.get("state").toString());
                resume.setHcity(parse1.get("hcity").toString());
                resume.setLastWork(parse1.get("last_work").toString());
                resume.setFileName(parse1.get("file_name").toString());
                resume.setManageSkillB((Boolean) parse1.get("manage_skill_b"));
                resume.setName(parse1.get("name").toString());
                resume.setHtrade(parse1.get("htrade").toString());
                resume.setResumeId(parse1.get("resume_id").toString());
                resume.setRefreshTime(Double.valueOf(parse1.get("refresh_time").toString()).longValue());
                resume.setPersonId(parse1.get("person_id").toString());
                resume.setSalaryTo((Integer) parse1.get("salary_to_i"));
                resume.setMarriaged(parse1.get("marriaged").toString());
                resume.setSource(parse1.get("source").toString());
                resume.setCurrentCity(parse1.get("current_city").toString());
                resume.setHukou(parse1.get("hukou").toString());
                resume.setAbroadWorkStudyB((Boolean) parse1.get("abroad_work_study_b"));
                resume.setEmail(parse1.get("email_s").toString());
                resume.setLastSchool(parse1.get("last_school").toString());
                resume.setLastEdu(parse1.get("last_edu").toString());
                resume.setLastJob(parse1.get("last_job").toString());

                this.resumeRepository.save(resume);
            }catch (Exception e) {
                continue;
            }
        }

        return "ok";
    }


    @RequestMapping("/getById")
    public Object getById(@RequestParam("id") String id) {
        return this.resumeRepository.findOne(id);
    }

    @RequestMapping("/getBySchoolAndDegreeCn")
    public Object getBySchoolAndDegreeCn(@RequestParam("school") String school, @RequestParam("degreeCn") String degreeCn) {
        return this.resumeRepository.findBySchoolsAndDegreeCn(school, degreeCn);
    }

    @RequestMapping("/getBySchoolOrDegreeCn")
    public Object getBySchoolOrDegreeCn(@RequestParam("school") String school, @RequestParam("degreeCn") String degreeCn) {
        return this.resumeRepository.findBySchoolsOrDegreeCn(school, degreeCn);
    }

}
